<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="auto"
    :inline-message="true"
  >
    <div>
      <el-upload
        ref="uploadRef"
        v-model:file-list="formData"
        :action="uploadUrl"
        :auto-upload="true"
        :disabled="formLoading"
        :on-change="handleFileChange"
        :on-error="submitFormError"
        :on-exceed="handleExceed"
        :on-success="submitFormSuccess"
        :http-request="httpRequest"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        accept=".jpg, .jpeg, .png, .gif"
        list-type="picture-card"
      >
        <el-icon><Plus /></el-icon>

        <template #file="{ file }">
          <div>
            <el-image style="width: 100%; height: 100%;" fit="cover" :src="file.imagePath" alt="" />
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <el-icon><zoom-in /></el-icon>
              </span>
              <span
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <el-icon><Delete /></el-icon>
              </span>
            </span>
          </div>
        </template>
      </el-upload>

      <el-dialog v-model="previewVisible" center>
        <template #header="{ titleId, titleClass }">
          <h4 :id="titleId" :class="titleClass">{{ dialogImageName }}</h4>
        </template>
        <el-row class="row-bg">
          <el-image style="max-width: 800px; max-height: 600px;" :src="dialogImageUrl" fit="cover"/>
        </el-row>
      </el-dialog>
    </div>
  </el-form>
</template>




<script setup lang="ts">
import { InfoApi } from '@/api/artifact/info'
import { InfoImageVO } from '@/api/artifact/info'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const props = defineProps<{
  artifactId: number // 文玩编号（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref<any[]>([])
const formRules = reactive({
  artifactId: [{ required: true, message: '文玩编号不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '名字不能为空', trigger: 'blur' }],
  imagePath: [{ required: true, message: '图片路径不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 图片上传 */
const uploadRef = ref()
const { uploadUrl, httpRequest } = useUpload()

/** 图片预览弹窗 */
const dialogImageUrl = ref('')
const dialogImageName = ref('')
const previewVisible = ref(false)

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.artifactId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await InfoApi.getInfoImageListByArtifactId(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

defineExpose({ validate, getData })

const handleRemove = (file: any) => {
  for (let i = 0; i < formData.value.length; i++) {
    let item = formData.value[i]
    if (item.uid === file.uid) {
      formData.value.splice(i, 1)
      return true
    }
  }
}

const handlePictureCardPreview = (file: InfoImageVO) => {
  dialogImageName.value = file.name
  dialogImageUrl.value = file.imagePath!
  previewVisible.value = true
}

/** 上传文件之前进行检查 */
const beforeUpload = () => {
}

/** 处理上传的文件发生变化 */
const handleFileChange = () => {
}

/** 文件上传成功处理 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitFormSuccess = (response: any) => {
  formData.value[formData.value.length-1].artifactId = props.artifactId
  formData.value[formData.value.length-1].imagePath = response.data

  // 提示成功，并刷新
  message.success(t('common.createSuccess'))
  emit('success')
  formLoading.value = false
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}
</script>
